package com.taotao.manage.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageInfo;
import com.taotao.common.bean.EasyUIResult;
import com.taotao.manage.pojo.Content;
import com.taotao.manage.service.ContentService;

/**
 * @Description: 内容控制层
 * @author:     mingxu
 */
@Controller
@RequestMapping("content")
public class ContentController {

	@Autowired
	private ContentService contentService;

	/**
	 * @Description:新增内容
	 * 	insert into tb_content values(.,.,..)
	 * 	请求地址：/rest/content POST
	 * 	请求参数 Content
	 * 	返回结果：Void 201 500
	 * 		
	 * @param content
	 * @return
	 * @author mingxu
	 */
	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity<Void> addContent(Content content) {
		try {
			contentService.save(content);
			return ResponseEntity.status(HttpStatus.CREATED).build();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();

	}

	/**
	 *	分页查询所有内容
	 *		select * from tb_content limit m,n
	 *	请求路径：/rest/content GET
	 *	请求参数：categoryId page rows
	 *	响应结果：EasyUIResult
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ResponseEntity<EasyUIResult> queryContentByPage(@RequestParam("categoryId") Long categoryId,
			@RequestParam("page") Integer page, @RequestParam("rows") Integer rows) {
		try {
			//分页查询，并根据更新时间排序
			PageInfo<Content> pageInfo = contentService.queryPageListByWhereOrderBy(Content.class, "updated desc", page,
					rows);

			if (pageInfo == null || pageInfo.getSize() == 0) {
				return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
			}

			//封装成前台所需的格式
			EasyUIResult result = new EasyUIResult();
			result.setTotal(pageInfo.getTotal());
			result.setRows(pageInfo.getList());
			return ResponseEntity.status(HttpStatus.OK).body(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);

	}
}
